import { Component } from '@angular/core';
import {Events, IonicPage, NavController, NavParams} from 'ionic-angular';
import {HttpService} from "../../providers/HttpService";
import {InfoProvider} from "../../providers/InfoProvider";

/**
 * Generated class for the TodayStrategyPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-today-strategy',
  templateUrl: 'today-strategy.html',
})
export class TodayStrategyPage {

    strategy_list: any[] = [];

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private events: Events,
                private infoProvider: InfoProvider,
                private httpService: HttpService) {
        if (this.infoProvider.isNative()) {
            this.events.subscribe('push:strategy', (data) => {
                console.log('push:strategy:', data);
                if (this.strategy_list.length > 0) {
                    this.strategy_list.unshift(data);
                } else {
                    this.getStrategy().then(res => {
                        if (res.status == 0) {
                            this.strategy_list = res.data.rows;
                        }
                    });
                }
            });
        }
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad TodayStrategyPage');
        this.getStrategy().then(res => {
            if (res.status == 0) {
                this.strategy_list = res.data.rows;
            }
        });
    }

    getStrategy(loader: boolean = true): Promise<any> {
        return new Promise((resolve, reject) => {
            this.httpService.instance().setUrl('/strategy/getStrategy')
                .setQuery({
                    start: 0,
                    size: 10,
                    orderKey: 'id',
                    orderVal: 'desc',
                    today: true
                })
                .showLoader(loader)
                .getRequest()
                .then(res => {
                    resolve(res);
                });
        });
    }

    onRefresh(refresher) {
        this.getStrategy(false).then(res => {
            if (res.status == 0) {
                this.strategy_list = res.data.rows;
            }
            refresher.complete();
        });
    }

    onItemSelected() {

    }
}
